<template>
  <div class="background">
    <div class="login-container">
      <el-card class="box-card">
        <div class="login-title">码上未来vue考试系统</div>
        <el-form :model="loginForm" ref="formRef" :rules="rules">
          <el-form-item prop="username">
            <el-input v-model="loginForm.username" style="width: 400px; margin: 10px 5px;" placeholder="账号" clearable size="large" :prefix-icon="User" />
          </el-form-item>
          <el-form-item prop="password">
            <el-input v-model="loginForm.password" style="width: 400px; margin: 10px 5px;" placeholder="密码" clearable type="password" size="large" :prefix-icon="Lock" />
          </el-form-item>
          <el-form-item prop="code">
            <span>
              <el-input v-model="loginForm.code" style="width: 290px; margin: 10px 5px;" placeholder="验证码" clearable size="large" :prefix-icon="ChatLineRound" />
              <img :src="codeImgUrl" alt="验证码" style="margin: 12px 3px;" class="code-img" title="看不清,点击刷新" @click="fetchCodeImage" />
            </span>
          </el-form-item>
          <div style="margin: 10px 0px 30px 7px;">
            <el-button type="primary" @click="handleLogin" size="large" style="width: 190px" :icon="Promotion"> 登录</el-button>
            <el-button type="warning" @click="handleRegister" size="large" style="width: 190px;" :icon="CirclePlus"> 学员注册</el-button>
          </div>
        </el-form>
      </el-card>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import axios from 'axios'
import { useRouter } from 'vue-router'
axios.defaults.baseURL = 'http://git.coding-future.com:7777/exam-server'
import { User, Lock, ChatLineRound, Promotion, CirclePlus } from '@element-plus/icons-vue';

const router = useRouter()

interface LoginForm {
  username: string
  password: string
  code: string
}

const loginForm = reactive<LoginForm>({
  username: '',
  password: '',
  code: '',
})

const codeImgUrl = ref('')
const formRef = ref(null)

const rules = {
  username: [
    { required: true, message: '请输入账号', trigger: 'blur' },
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 5, message: '密码不得少于5个字符', trigger: 'blur' }
  ],
  code: [
    { required: true, message: '请输入验证码', trigger: 'blur' },
  ]
}

// 获取验证码图片
async function fetchCodeImage() {
  try {
    const id = new Date().getTime().toString()
    const response = await axios.get('/util/getCodeImg', {
      params: { id },
      responseType: 'blob',
    })
    const url = URL.createObjectURL(response.data)
    codeImgUrl.value = url
  } catch (error) {
    console.error('Error fetching code image:', error)
  }
}

// 登录处理
async function handleLogin() {
  try {
    const valid = await formRef.value?.validate()
    if (!valid) return

    const formData = new FormData()
    formData.append('username', loginForm.username)
    formData.append('password', loginForm.password)

    const response = await axios.post('/common/login', formData, {
      headers: {
        'Content-Type': 'multipart/form-data',
      },
    })

    const token = response.data.data
    if (token) {
      localStorage.setItem('username', loginForm.username)
      localStorage.setItem('token', token)
      router.push('/home/dashboard')
    }
  } catch (error) {
    if (error.response) {
      console.error('Error during login:', {
        status: error.response.status,
        data: error.response.data,
      })
    } else if (error.request) {
      console.error('Error during login:', error.request)
    } else {
      console.error('Error during login:', error.message)
    }
  }
}

async function handleRegister() {
  // 学员注册
}

// 初始化验证码图片
onMounted(() => {
  fetchCodeImage()
})
</script>

<style scoped>
.background {
  background-image: url(../assets/bg.jpeg);
  background-size: cover;
  background-position: center;
  height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
}

.login-container {
  width: 450px;
  margin: 100px auto;
  padding: 20px;
}

.login-title {
  font-size: 20px;
  text-align: center;
  margin-bottom: 20px;
}

.code-img {
  width: 95px;
  height: 30px;
  border: 1px solid #c5cad5;
  border-radius: 4px;
  float: right;
  cursor: pointer;
}
</style>
